package com.ys.controller.api.finance;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ys.enume.flow.FlowEnum;
import com.ys.service.flow.YspTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bo.util.DateUtil;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliReconciliation;
import com.ys.entity.finance.TcwWanliReconciliationItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.mapper.finance.FinanceMapper;
import com.ys.service.finance.TcwWanliReconciliationService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcwWanliReconciliation")
public class ApiInterTcwWanliReconciliationController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private FinanceMapper financeMapper;
	@Autowired
	private CommonApiService<TcwWanliReconciliation> commonApiService;
	@Autowired
	private CommonApiService<TcwWanliReconciliationItem> commonApiServiceDetail;
	@Autowired
	private TcwWanliReconciliationService tcwWanliReconciliationService;
	
	@RequiresPermissions("tcwWanliReconciliation:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwWanliReconciliationItem cond){
		
		cond = setSeachSql(cond);
		return commonApiServiceDetail.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("tcwWanliReconciliation:add")
	public R add(String bid, String depositPlatformCode, String reconciliationDayBegin, String reconciliationDayEnd, String vbz,
			BigDecimal amountGbp,
			BigDecimal amountUsd,
			BigDecimal amountEur,
			BigDecimal amountCny,
			BigDecimal feeGbp,
			BigDecimal feeUsd,
			BigDecimal feeEur,
			BigDecimal amountGuijiGbp,
			BigDecimal amountGuijiUsd,
			BigDecimal amountGuijiEur, String subData) {
		try {
			//修改
			return tcwWanliReconciliationService.add(bid, depositPlatformCode, reconciliationDayBegin, reconciliationDayEnd, vbz,
					amountGbp,
					amountUsd,
					amountEur,
					amountCny,
					feeGbp,
					feeUsd,
					feeEur,
					amountGuijiGbp,
					amountGuijiUsd,
					amountGuijiEur, subData, MenuId.TCW_WanliReconciliation);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequiresPermissions("tcwWanliReconciliation:add")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(String bid, String depositPlatformCode, String reconciliationDayBegin, String reconciliationDayEnd, String vbz,
			BigDecimal amountGbp,
			BigDecimal amountUsd,
			BigDecimal amountEur,
			BigDecimal amountCny,
			BigDecimal feeGbp,
			BigDecimal feeUsd,
			BigDecimal feeEur,
			BigDecimal amountGuijiGbp,
			BigDecimal amountGuijiUsd,
			BigDecimal amountGuijiEur, String subData){
		try {
			return tcwWanliReconciliationService.edit(bid, depositPlatformCode, reconciliationDayBegin, reconciliationDayEnd, vbz,
					amountGbp,
					amountUsd,
					amountEur,
					amountCny,
					feeGbp,
					feeUsd,
					feeEur,
					amountGuijiGbp,
					amountGuijiUsd,
					amountGuijiEur, subData, MenuId.TCW_WanliReconciliation);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("tcwWanliReconciliation:add")
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		TcwWanliReconciliation tcwWanliReconciliation = new TcwWanliReconciliation().setId(id).queryFirst();
		try {
			return tcwWanliReconciliationService.flowPass(tcwWanliReconciliation.getBid(), ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwWanliReconciliation:add")
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		TcwWanliReconciliation tcwWanliReconciliation = new TcwWanliReconciliation().setId(id).queryFirst();
		try {
			return tcwWanliReconciliationService.flowRefuse(tcwWanliReconciliation.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}


	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwWanliReconciliation:add")
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		TcwWanliReconciliation tcwWanliReconciliation = new TcwWanliReconciliation().setId(id).queryFirst();
		try {
			return yspTaskService.flowInit(tcwWanliReconciliation.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 删除
	 * @throws Exception 
	 */
	@RequiresPermissions("tcwWanliReconciliation:add")
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return tcwWanliReconciliationService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tcwWanliReconciliation:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliReconciliationItem cond) throws Exception{
		
		cond = setSeachSql(cond);
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCW_WanliPrepaymentPooling)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TcwWanliReconciliation> util = new ExportExcelUtils<TcwWanliReconciliation>(new TcwWanliReconciliation());
        
        String toFilePath = util.exportExcel(listData, listField, "万里汇预付款对账单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwWanliReconciliationItem setSeachSql(TcwWanliReconciliationItem cond){
    	
    	cond.addLeftJoin("TCW_WanliReconciliation B ON B.Bid = A.Pbid")
	    		.addField("B.Bid bid")
	    		.addField("B.EffectStock effectStock")
	    		.addField("B.ReconciliationDayBegin reconciliationDayBegin")
	    		.addField("B.ReconciliationDayEnd reconciliationDayEnd")
	    		.addField("B.Vbz vbz")
	    		.addField("B.AmountGbp amountGbp")
	    		.addField("B.AmountUsd amountUsd")
	    		.addField("B.AmountEur amountEur")
	    		.addField("B.FeeGbp feeGbp")
	    		.addField("B.FeeUsd feeUsd")
	    		.addField("B.FeeEur feeEur")
	    		.addField("B.AmountGuijiGbp amountGuijiGbp")
	    		.addField("B.AmountGuijiUsd amountGuijiUsd")
	    		.addField("B.AmountGuijiEur amountGuijiEur")
    		.addLeftJoin("YS_ProcInst B99 ON B99.Bid = B.Bid")
	    		.addField("B99.UpdateTime auditTime")
	    		.addField("B99.CreateUserId createUserId")
    		.addLeftJoin("TS_UserInfo B100 ON B100.UserId = B99.CreateUserId")
	    		.addField("B100.UserId createUserId")
	    		.addField("B100.UserName createUserName");
    	
    	cond.addLeftJoin("TCW_DepositPlatform C on C.Code = B.DepositPlatformCode")
			.addField("C.PlatformName platformName")
			.addField("C.Code depositPlatformCode")
			.addField("C.Name depositPlatformName");
    	
    	cond.addLeftJoin("TB_CompanyInfo C1 on C1.Vid = C.CompanyVid")
			.addField("C1.Vid companyVid")
			.addField("C1.Vname companyVname");
		
    	cond.addLeftJoin("TCW_WanliPrepaymentPooling BB ON BB.Id = A.WanliPrepaymentPoolingId")
			.addField("BB.FkMid fkMid")
			.addField("BB.PayerAccountNo payerAccountNo")
			.addField("BB.PayerName payerName")
			.addField("BB.SkMid skMid")
			.addField("BB.BeneficiaryAccountNo beneficiaryAccountNo")
			.addField("BB.BeneficiaryName beneficiaryName")
			.addField("BB.TransactionType transactionType")
			.addField("BB.OriginalTransactionAmount originalTransactionAmount")
			.addField("BB.JyCurrencyCode jyCurrencyCode")
			.addField("BB.ExtTransactionId extTransactionId")
			.addField("BB.TransactionId transactionId")
			.addField("BB.TransactionTime transactionTime")
			.addField("BB.TransactionStatus transactionStatus")
			.addField("BB.Description description")
			.addField("BB.fkVyhsx fkVyhsx")
			.addField("BB.skVyhsx skVyhsx");

    	cond.addLeftJoin("THR_OperateCompanyApply B3 ON B3.vgsbm = BB.vgsbm")//运营公司
			.addField("B3.vgsbm vgsbm")
			.addField("B3.vgsjc vgsjc");
		
        return  cond;
    }

	/**
	 * 获取各个金额
	 */
	@PostMapping("/getAmounts")
    @ResponseBody
	public R getAmounts(String reconciliationDayBegin, String reconciliationDayEnd,String bid){
		if (reconciliationDayEnd == null || reconciliationDayEnd.length() == 0) {
			return R.error();
		}

		Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();

		TcwWanliReconciliation entity = new TcwWanliReconciliation().setBid(bid).queryFirst();
		if(entity!=null && entity.getEffectStock()!=null && entity.getEffectStock()== FlowEnum.EffectStock.EFFECTED.value){
			map.put("amountGbp",entity.getAmountGbp());
			map.put("amountUsd",entity.getAmountUsd());
			map.put("amountEur",entity.getAmountEur());
			map.put("amountCny",entity.getAmountCny());
			map.put("feeGbp",entity.getFeeGbp());
			map.put("feeUsd",entity.getFeeUsd());
			map.put("feeEur",entity.getFeeEur());
			return R.ok(map);
		}

		reconciliationDayBegin = DateUtil.getYYYY_MM_DD(DateUtil.addDays(reconciliationDayBegin, 1));
		reconciliationDayEnd = DateUtil.getYYYY_MM_DD(DateUtil.addDays(reconciliationDayEnd, 1));
		

		
		// GBP使用金额
		{
			String currencyCode = "GBP";
			BigDecimal currencyExchangeOut = financeMapper.sumWanliCurrencyExchangeOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal currencyExchangeIn = financeMapper.sumWanliCurrencyExchangeIn(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal drawingIn = financeMapper.sumWanliDrawingOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal cnyPaymentOut = financeMapper.sumWanliCnyPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal paymentReturnOut = financeMapper.sumWanliPaymentReturnOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal otherPaymentOut = financeMapper.sumWanliOtherPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			map.put("amountGbp",
					currencyExchangeOut.subtract(currencyExchangeIn)
					.add(drawingIn)
					.add(cnyPaymentOut)
					.add(paymentReturnOut)
					.add(otherPaymentOut)
					);
		}
		
		// USD使用金额
		{
			String currencyCode = "USD";
			BigDecimal currencyExchangeOut = financeMapper.sumWanliCurrencyExchangeOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal currencyExchangeIn = financeMapper.sumWanliCurrencyExchangeIn(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal drawingIn = financeMapper.sumWanliDrawingOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal cnyPaymentOut = financeMapper.sumWanliCnyPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal paymentReturnOut = financeMapper.sumWanliPaymentReturnOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal otherPaymentOut = financeMapper.sumWanliOtherPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			map.put("amountUsd",
					currencyExchangeOut.subtract(currencyExchangeIn)
					.add(drawingIn)
					.add(cnyPaymentOut)
					.add(paymentReturnOut)
					.add(otherPaymentOut)
					);
		}
		
		// EUR使用金额
		{
			String currencyCode = "EUR";
			BigDecimal currencyExchangeOut = financeMapper.sumWanliCurrencyExchangeOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal currencyExchangeIn = financeMapper.sumWanliCurrencyExchangeIn(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal drawingIn = financeMapper.sumWanliDrawingOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal cnyPaymentOut = financeMapper.sumWanliCnyPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal paymentReturnOut = financeMapper.sumWanliPaymentReturnOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal otherPaymentOut = financeMapper.sumWanliOtherPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			map.put("amountEur",
					currencyExchangeOut.subtract(currencyExchangeIn)
					.add(drawingIn)
					.add(cnyPaymentOut)
					.add(paymentReturnOut)
					.add(otherPaymentOut)
					);
		}
		
		// CNY金额
		{
			BigDecimal amountCny = financeMapper.sumAmountCNY(reconciliationDayBegin, reconciliationDayEnd);
			map.put("amountCny", amountCny);
		}
		
		// GBP手续费
		{
			String currencyCode = "GBP";
			BigDecimal drawingIn = financeMapper.sumFeeWanliDrawingOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal cnyPaymentOut = financeMapper.sumFeeWanliCnyPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal paymentReturnOut = financeMapper.sumFeeWanliPaymentReturnOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal otherPaymentOut = financeMapper.sumFeeWanliOtherPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			map.put("feeGbp",
					drawingIn
					.add(cnyPaymentOut)
					.add(paymentReturnOut)
					.add(otherPaymentOut)
					);
		}
		
		// USD手续费
		{
			String currencyCode = "USD";
			BigDecimal drawingIn = financeMapper.sumFeeWanliDrawingOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal cnyPaymentOut = financeMapper.sumFeeWanliCnyPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal paymentReturnOut = financeMapper.sumFeeWanliPaymentReturnOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal otherPaymentOut = financeMapper.sumFeeWanliOtherPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			map.put("feeUsd",
					drawingIn
					.add(cnyPaymentOut)
					.add(paymentReturnOut)
					.add(otherPaymentOut)
					);
		}
		
		// EUR手续费
		{
			String currencyCode = "EUR";
			BigDecimal drawingIn = financeMapper.sumFeeWanliDrawingOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal cnyPaymentOut = financeMapper.sumFeeWanliCnyPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal paymentReturnOut = financeMapper.sumFeeWanliPaymentReturnOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			BigDecimal otherPaymentOut = financeMapper.sumFeeWanliOtherPaymentOut(currencyCode, reconciliationDayBegin, reconciliationDayEnd);
			map.put("feeEur",
					drawingIn
					.add(cnyPaymentOut)
					.add(paymentReturnOut)
					.add(otherPaymentOut)
					);
		}
		
		return R.ok(map);
	}
}
